package code12线程;



/**
 * @author 黄衡熙
 * @version 1.0
 */
/*
*
* 定义两个线程分别打印不同的内容,要求两个线程之间交替执行10次
//例如第一个线程打印Hello,第二个线程打印World
//其结果为HelloWorldHelloWorldHelloWorldHelloWorld....
//或者WorldHelloWorldHelloWorldHelloWorldHello...*/
public class Test08_交替练习 {
    public static void main(String[] args) {
        Object obj=new Object();
        HelloThread t1 = new HelloThread(obj);
        WorldThread t2 = new WorldThread(obj);
        t1.start();
        t2.start();

    }
}

class HelloThread extends Thread {
   private Object obj;
    public HelloThread(Object obj) {
        this.obj = obj;
    }
    public void run() {
        synchronized (obj) {
        for (int i = 0; i < 10; i++) {
                System.out.print("Hello");
               obj.notifyAll();
            try {
                obj.wait();
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        }
        }
    }
}

class WorldThread extends Thread {
    private Object obj;
    public WorldThread(Object obj) {
        this.obj = obj;
    }
    public void run() {
        synchronized (obj) {
        for (int i = 0; i < 10; i++) {
                System.out.print("World");
               obj.notifyAll();
            try {
                obj.wait();
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        }
        }
    }
}